<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 管理员后台</title>
    <link rel="stylesheet" href="css/style.css">
    <style>
        .container {
            padding: 20px;
        }
        .search-bar {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .search-bar input, .search-bar select, .search-bar button {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .user-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .user-table th, .user-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .user-table th {
            background-color: #f5f5f5;
        }
        .action-btn {
            margin: 0 5px;
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .edit-btn {
            background-color: #4CAF50;
            color: white;
        }
        .delete-btn {
            background-color: #f44336;
            color: white;
        }
        .status-active {
            color: green;
        }
        .status-inactive {
            color: red;
        }
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        .pagination button {
            padding: 5px 10px;
            border: 1px solid #ddd;
            background-color: white;
            cursor: pointer;
        }
        .pagination button.active {
            background-color: #4CAF50;
            color: white;
            border-color: #4CAF50;
        }
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 5px;
            width: 50%;
        }
        .close-btn {
            float: right;
            cursor: pointer;
            font-size: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>用户管理</h1>
        <div class="search-bar">
            <input type="text" id="keyword" placeholder="搜索用户名/邮箱">
            <select id="roleFilter">
                <option value="">所有角色</option>
                <option value="admin">管理员</option>
                <option value="company">企业用户</option>
                <option value="job-seeker">求职者</option>
            </select>
            <select id="statusFilter">
                <option value="">所有状态</option>
                <option value="active">正常</option>
                <option value="inactive">禁用</option>
            </select>
            <button onclick="searchUsers()">搜索</button>
            <button onclick="resetSearch()">重置</button>
        </div>
        <table class="user-table">
            <thead>
                <tr>
                    <th>用户名</th>
                    <th>昵称</th>
                    <th>邮箱</th>
                    <th>角色</th>
                    <th>注册时间</th>
                    <th>账号状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="userTableBody">
                <!-- 用户数据将通过JavaScript动态加载 -->
            </tbody>
        </table>
        <div class="pagination" id="pagination">
            <!-- 分页按钮将通过JavaScript动态加载 -->
        </div>
    </div>

    <!-- 用户编辑模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close-btn" onclick="closeModal()">&times;</span>
            <h2>编辑用户</h2>
            <form id="editUserForm">
                <input type="hidden" id="userId">
                <div class="form-group">
                    <label for="editName">用户名</label>
                    <input type="text" id="editName" readonly>
                </div>
                <div class="form-group">
                    <label for="editEmail">邮箱</label>
                    <input type="email" id="editEmail" readonly>
                </div>
                <div class="form-group">
                    <label for="editRole">角色</label>
                    <select id="editRole">
                        <option value="company">企业用户</option>
                        <option value="job-seeker">求职者</option>
                        <option value="admin">管理员</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editStatus">状态</label>
                    <select id="editStatus">
                        <option value="active">正常</option>
                        <option value="inactive">禁用</option>
                    </select>
                </div>
                <button type="submit">保存</button>
            </form>
        </div>
    </div>

    <script src="js/auth.js"></script>
    <script>
        // 页面加载时验证管理员权限并加载用户列表
        document.addEventListener('DOMContentLoaded', function() {
            const userRole = getUserRole();
            // 管理员直接访问，无需登录检查
            // 实际生产环境中应恢复权限验证
            // if (!userRole || userRole !== 'admin') {
            //     alert('没有管理员权限，将跳转到登录页面');
            //     window.location.href = 'admin-login.html';
            //     return;
            // }
            loadUsers();
        });

        // 加载用户列表
        async function loadUsers(page = 1) {
            const keyword = document.getElementById('keyword').value;
            const role = document.getElementById('roleFilter').value;
            const status = document.getElementById('statusFilter').value;
            const token = getToken();

            try {
                const response = await fetch(`http://localhost:3000/api/admin/users?page=${page}&limit=10&keyword=${keyword}&role=${role}&status=${status}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                const data = await response.json();
                if (data.success) {
                    renderUserTable(data.data.users);
                    renderPagination(data.data.pagination);
                } else {
                    alert(data.message || '加载用户列表失败');
                }
            } catch (error) {
                console.error('加载用户失败:', error);
                alert('网络错误，请稍后重试');
            }
        }

        // 渲染用户表格
        function renderUserTable(users) {
            const tableBody = document.getElementById('userTableBody');
            tableBody.innerHTML = '';

            users.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${user.username || '-'}</td>
                    <td>${user.name || '-'}</td>
                    <td>${user.email}</td>
                    <td>${formatRole(user.role)}</td>
                    <td>${formatDate(user.createdAt)}</td>
                    <td class="status-${user.status}">${user.status === 'active' ? '正常' : '禁用'}</td>
                    <td>
                        <button class="action-btn edit-btn" onclick="openEditModal(${JSON.stringify(user)})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteUser(${user.id})">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 渲染分页控件
        function renderPagination(pagination) {
            const paginationDiv = document.getElementById('pagination');
            paginationDiv.innerHTML = '';

            for (let i = 1; i <= pagination.pages; i++) {
                const button = document.createElement('button');
                button.textContent = i;
                if (i === pagination.page) {
                    button.classList.add('active');
                }
                button.onclick = () => loadUsers(i);
                paginationDiv.appendChild(button);
            }
        }

        // 搜索用户
        function searchUsers() {
            loadUsers(1);
        }

        // 重置搜索
        function resetSearch() {
            document.getElementById('keyword').value = '';
            document.getElementById('roleFilter').value = '';
            document.getElementById('statusFilter').value = '';
            loadUsers(1);
        }

        // 打开编辑模态框
        function openEditModal(user) {
            document.getElementById('userId').value = user.id;
            document.getElementById('editName').value = user.username || '';
            document.getElementById('editEmail').value = user.email || '';
            document.getElementById('editRole').value = user.role || 'job-seeker';
            document.getElementById('editStatus').value = user.status || 'active';
            document.getElementById('editModal').style.display = 'block';
        }

        // 关闭编辑模态框
        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 删除用户
        async function deleteUser(userId) {
            if (!confirm('确定要删除此用户吗？此操作不可恢复！')) {
                return;
            }

            const token = getToken();
            try {
                const response = await fetch(`http://localhost:3000/api/admin/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                const data = await response.json();
                if (data.success) {
                    alert('用户删除成功');
                    loadUsers();
                } else {
                    alert(data.message || '删除用户失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('网络错误，请稍后重试');
            }
        }

        // 提交编辑用户表单
        document.getElementById('editUserForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const userId = document.getElementById('userId').value;
            const role = document.getElementById('editRole').value;
            const status = document.getElementById('editStatus').value;
            const token = getToken();

            try {
                // 先更新角色
                if (role) {
                    await fetch(`http://localhost:3000/api/admin/users/${userId}/role`, {
                        method: 'PUT',
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ role })
                    });
                }

                // 再更新状态
                if (status !== undefined) {
                    await fetch(`http://localhost:3000/api/admin/users/${userId}/status`, {
                        method: 'PUT',
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ status })
                    });
                }

                alert('用户信息更新成功');
                closeModal();
                loadUsers();
            } catch (error) {
                console.error('更新用户失败:', error);
                alert('更新用户失败，请重试');
            }                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token}`
                        },
                        body: JSON.stringify({ role })
                    });
                }

                // 再更新状态
                await fetch(`http://localhost:3000/api/admin/users/${userId}/status`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ status })
                });

                closeModal();
                loadUsers();
                alert('用户信息更新成功');
            } catch (error) {
                console.error('更新用户失败:', error);
                alert('更新用户失败，请重试');
            }
        });

        // 删除用户
        async function deleteUser(userId) {
            if (!confirm('确定要删除此用户吗？此操作不可恢复。')) {
                return;
            }

            const token = getToken();
            try {
                const response = await fetch(`http://localhost:3000/api/admin/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                const data = await response.json();
                if (data.success) {
                    loadUsers();
                    alert('用户删除成功');
                } else {
                    alert(data.message || '删除用户失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('网络错误，请稍后重试');
            }
        }

        // 格式化角色显示
        function formatRole(role) {
            switch(role) {
                case 'admin': return '管理员';
                case 'company': return '企业用户';
                case 'job-seeker': return '求职者';
                default: return role;
            }
        }

        // 格式化日期显示
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleString();
        }
    </script>
</body>
</html>